package com.yhy.manager.controller;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import com.yhy.manager.domain.Admin;
import com.yhy.manager.domain.vo.AdminVo;
import com.yhy.manager.interceptor.AdminHolder;
import com.yhy.manager.service.AdminService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;

@RestController
@RequestMapping("/system/users")
public class SystemController {

    @Autowired
    private AdminService adminService;

    /**
     * 用户登录验证码图片
     *
     * 接口路径：GET/system/users/verification
     *
     * 请求参数: Query
     *      uuid:浏览器生成随机id
     *
     * 返回值: void 内部生成图片 以流的形式返回给浏览器
     */
    @GetMapping("/verification")
    public void verification(String uuid, HttpServletResponse response) throws IOException {
        //1、数据响应配置参数
        response.setDateHeader("Expires", 0);
        // Set standard HTTP/1.1 no-cache headers.
        response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
        // Set IE extended HTTP/1.1 no-cache headers (use addHeader).
        response.addHeader("Cache-Control", "post-check=0, pre-check=0");
        // Set standard HTTP/1.0 no-cache header.
        response.setHeader("Pragma", "no-cache");
        response.setContentType("image/jpeg");
        //2.通过工具类生成验证码图片
        LineCaptcha captcha = CaptchaUtil.createLineCaptcha(299, 97);
        String code = captcha.getCode();
        //3.调用service将验证码存入redis
        adminService.saveCap(uuid,code);
        //4.输出流返回图片
        captcha.write(response.getOutputStream());
    }

    /**
     * 用户登录
     *
     * 接口路径：POST/system/users/login
     *
     * 请求参数:Body
     *      username: 账号
     *      password: 密码
     *      verificationCode: 验证码
     *      uuid: 同获取验证码时的uuid
     *
     * 返回值: token
     */
    @PostMapping("/login")
    public ResponseEntity login(@RequestBody Map map){
        return adminService.login(map);
    }

    /**
     * 用户基本信息
     *
     * 接口路径：POST/system/users/profile
     *
     * 请求参数: 无
     *
     * 返回值:
     *      id: 用户id
     *      username: 账号
     *      avatar: 头像
     */
    @PostMapping("/profile")
    public ResponseEntity profile(){
        Admin admin = AdminHolder.getAdmin();
        AdminVo vo = AdminVo.init(admin);
        return ResponseEntity.ok(vo);
    }

    /**
     * 用户登出
     *
     * 接口路径：POST/system/users/logout
     *
     * 请求参数: token
     *
     * 返回值: null
     */
    @PostMapping("/logout")
    public ResponseEntity logout(@RequestHeader("Authorization") String token){
        return adminService.logout(token);
    }

    /**
     *
     */
}
